 require([
           "esri/map","esri/graphic","esri/geometry/Point","esri/SpatialReference","esri/tasks/GeometryService","esri/geometry/Polygon",
           "esri/tasks/LengthsParameters","esri/tasks/AreasAndLengthsParameters","esri/tasks/FindTask","esri/tasks/FindParameters",
           "esri/tasks/query","esri/tasks/QueryTask","esri/dijit/Print",
           "esri/tasks/IdentifyTask",
           "esri/tasks/IdentifyParameters",
           "esri/dijit/Popup",
           "esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/ArcGISDynamicMapServiceLayer","esri/layers/FeatureLayer", 
           "esri/tasks/ClassBreaksDefinition", "esri/tasks/AlgorithmicColorRamp","esri/geometry/screenUtils",
           "esri/tasks/GenerateRendererParameters", "esri/tasks/GenerateRendererTask","esri/dijit/OverviewMap","esri/dijit/BasemapGallery","esri/dijit/Scalebar",
           "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleFillSymbol", 
           "esri/toolbars/draw","esri/toolbars/navigation",
           "esri/dijit/PopupTemplate", "esri/dijit/Legend", "esri/config",
           "dojo/parser", "dojo/_base/array", "dojo/_base/lang","dojox/encoding/base64","esri/Color","dojo/on","dojo/dom-attr","dojo/dom-class","dojo/dom-style","dojo/query",
           "dojo/dom", "dojo/dom-construct","dijit/registry","dojo/json","dojo/DeferredList", "dojo/_base/Deferred",
           "dojo/domReady!"
         ], function(
           Map, Graphic,Point,SpatialReference,GeometryService,Polygon,
           LengthsParameters,AreasAndLengthsParameters,FindTask,FindParameters,
           Query, QueryTask,Print,
           IdentifyTask, IdentifyParameters, Popup,
           ArcGISTiledMapServiceLayer, ArcGISDynamicMapServiceLayer,FeatureLayer, 
           ClassBreaksDefinition, AlgorithmicColorRamp,screenUtils,
           GenerateRendererParameters, GenerateRendererTask,OverviewMap,BasemapGallery,Scalebar,
           SimpleLineSymbol, SimpleFillSymbol, 
           Draw,Navigation,
           PopupTemplate, Legend,esriConfig,
           parser, arrayUtils,lang,base64,Color,on,
           domAttr,domClass,domStyle,query,dom, domConstruct,registry,JSON,DeferredList, Deferred
         ) {
        "use strict"
        var identifyTask, identifyParams;
        var allQueryResult=[];
       /* var popup = new Popup({
            fillSymbol: new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
              new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.25]))
          }, domConstruct.create("div"));*/
          //78, 171, 214
        var tb; 
          //高亮线符号
    	var highlightSymbol=new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0 ]), 7);
          //高亮面符号
    	var highlightFillSymbol= new esri.symbol.SimpleFillSymbol("solid", null,  new Color([255, 0, 0, 0.50]));
    	var diseaseSymbol=esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/tools/arrow-green.png", 52, 52); //标识
    	var baseViewmap = new ArcGISTiledMapServiceLayer(appConfig.gisPath+"/arcgis/rest/services/longhua/basemap/MapServer"); //底图
    	var sdRef = new ArcGISDynamicMapServiceLayer(appConfig.gisPath+"/arcgis/rest/services/longhua/jtgh/MapServer",{ "id": "facility" });  // 规划
    	var xzRef = new ArcGISDynamicMapServiceLayer(appConfig.gisPath+"/arcgis/rest/services/longhua/jtxz/MapServer");  // 现状
    	var jsRef = new ArcGISDynamicMapServiceLayer(appConfig.gisPath+"/arcgis/rest/services/longhua/jsxm/MapServer");  // 建设项目
        // Create map
        var map = new Map("mapDiv", {
          zoom: 15
        });
        map.addLayers([baseViewmap,xzRef,sdRef,jsRef]);
       // Wire events
        on(map, "load", initMap);
        //添加项目信息查询按钮和事件
        var link = domConstruct.create("a",{
            "class": "action",
            "id": "ProjectInfoLink",
            "innerHTML": "项目信息", //text that appears in the popup for the link
            "href": "javascript: void(0);"
        }, query(".actionList", map.infoWindow.domNode)[0]);
        
        //绑定项目信息事件
        on(link, "click", QueryProjectInfo);
       //添加缩略图
        var overviewMapDijit = new OverviewMap({
            map: map,
            visible: false, //初始不显示
            attachTo:"bottom-right"
        });
        overviewMapDijit.startup();
        //添加地图比例尺
        var scalebar = new Scalebar({
            map: map,
            // "dual" displays both miles and kilmometers
            // "english" is the default, which displays miles
            // use "metric" for kilometers
            scalebarUnit: "metric",
            scalebarStyle:"ruler"
        });
        
        // 通过参数初始化地图
        function initMap() {
        	var stext = dom.byId("stext").value;
        	var type = dom.byId("type").value;
        	if(type =="1") {
        		findQQXM(stext);
        	}else if(type =="2") {
        		findSGXM(stext);
        	}
            //create identify tasks and setup parameters
        	var QueryUrl=appConfig.gisPath+"/arcgis/rest/services/longhua/jtxz/MapServer";
            identifyTask = new IdentifyTask(QueryUrl);

            identifyParams = new IdentifyParameters();
            identifyParams.tolerance = 3;
            identifyParams.returnGeometry = true;
            identifyParams.layerIds = GetAllLayerIds(QueryUrl);
            identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_ALL;
            identifyParams.width = map.width;
            identifyParams.height = map.height;
            map.on("click", executeIdentifyTask);
        }
        
        function QueryProjectInfo(evt){
            //display a message so user knows something is happening
            //domAttr.set(dom.byId("statsLink"), "innerHTML", "Calculating...");
        }
        //点击查询事件
        function executeIdentifyTask (event) {
            identifyParams.geometry = event.mapPoint;
            identifyParams.mapExtent = map.extent;

            var deferred = identifyTask
              .execute(identifyParams)
              .addCallback(function (response) {
                // response is an array of identify result objects
                // Let's return an array of features.
                return arrayUtils.map(response, function (result) {
                  var feature = result.feature;
                  var layerName = result.layerName;
                  var infoTemplate = new esri.InfoTemplate(layerName,  buildTemplateColumns(feature.attributes));
                  feature.setInfoTemplate(infoTemplate);
                  return feature;
                });
              });

            // InfoWindow expects an array of features from each deferred
            // object that you pass. If the response from the task execution
            // above is not an array of features, then you need to add a callback
            // like the one above to post-process the response and return an
            // array of features.
            map.infoWindow.setFeatures([deferred]);
            map.infoWindow.show(event.mapPoint);
          }
        function getGeometryCenter (geometry) {
       	 var point;
       	  switch(geometry.type){
       	    case "point":
       	    	point =geometry;
       	      break;
       	    case "polyline":
       	    	point =geometry.getExtent().getCenter();
       	      break;
       	    case "polygon":
       	    	point =geometry.getExtent().getCenter();
       	      break;
       	  }
       	  return point;
       }

       function getGeometryExtent (geometry) {
       	 var extent;
       	  switch(geometry.type){
       	    case "point":
       	    	extent =geometry;
       	      break;
       	    default: 
       	    	extent =geometry.getExtent();
       	  }
       	  return extent;
       }
      /* 前期项目**/
       function findQQXM(stext) {
    		var searchurl = appConfig.gisPath+"/arcgis/rest/services/longhua/jsxm/MapServer";  
    		var findParams = new FindParameters(); 
    	      findParams.returnGeometry = true; 
    	      findParams.layerIds = [1,2,3,4,5,6,7,8,9,10,11,12,13]; 
    	      findParams.searchFields = ["项目名称","项目编号"];
    	      findParams.searchText = stext; 
    	      var findTask = new esri.tasks.FindTask(searchurl);
    	      findTask.execute(findParams, function(findResults){
    	      	if(findResults.length==0){
    	      		return;
    	      	}
    	          map.graphics.clear();
    	          map.infoWindow.hide();
    	          var extent;
    	          var showGraphic;
    	          var graphic;
    	      	var data = arrayUtils.map(findResults, function(findResult,index) {
    	      		 graphic = findResult.feature;
    	  				setGraphicSymbol(findResult.feature);
    	  				summaryInfo(graphic);
    	  				map.graphics.add(graphic);
    	  				
    	  				extent =getGeometryExtent(graphic.geometry,extent);
    	  				showGraphic = graphic;
    	            });
    	      	var deferred = map.setExtent(extent,true);
    	      	Queryjtgh(graphic);
    			deferred.then(function(){
  				var centrPoint =map.extent.getCenter();
  				
                var screenPoint = map.toScreen(centrPoint);
//    				map.infoWindow.setTitle(showGraphic.getTitle());
//    		        map.infoWindow.setContent(showGraphic.getContent());
//    		        map.infoWindow.show(centrPoint,map.getInfoWindowAnchor(screenPoint));
    			  });
    	      }); 
    		
    	}

       /* 前期项目**/
       function findSGXM(stext) {
    		var searchurl = appConfig.gisPath+"/arcgis/rest/services/longhua/jsxm/MapServer";  
    		var findParams = new FindParameters(); 
    	      findParams.returnGeometry = true; 
    	      findParams.layerIds = [15,16,17,18,19,20,21,22,23,24,25,26,27]; 
    	      findParams.searchFields = ["项目名称","项目编号"];
    	      findParams.searchText = stext; 
    	      var findTask = new esri.tasks.FindTask(searchurl);
    	      findTask.execute(findParams, function(findResults){
    	      	if(findResults.length==0){
    	      		return;
    	      	}
    	          map.graphics.clear();
    	          map.infoWindow.hide();
    	          var extent;
    	          var showGraphic;
    	      	var data = arrayUtils.map(findResults, function(findResult,index) {
    	      		var graphic = findResult.feature;
    	  				setGraphicSymbol(findResult.feature);
    	  				summaryInfo(graphic);
    	  				map.graphics.add(graphic);
    	  				extent =getGeometryExtent(graphic.geometry,extent);
    	  				showGraphic = graphic;
    	            });
    	      	var deferred = map.setExtent(extent,true);
    			deferred.then(function(){
//    				var centrPoint =map.extent.getCenter();
//    				var screenPoint = map.toScreen(centrPoint);
//    				map.infoWindow.setTitle(showGraphic.getTitle());
//    		        map.infoWindow.setContent(showGraphic.getContent());
//    		        map.infoWindow.show(centrPoint,map.getInfoWindowAnchor(screenPoint));
    			  });
    	      }); 
    		
    	}
     //设置高亮的模式
       function setGraphicSymbol(graphic) {
       	var geometry  = graphic.geometry;
       	  switch(geometry.type){
       	    case "point":
       	    	 graphic.setSymbol(diseaseSymbol);
       	      break;
       	    case "polyline":
       	    	 graphic.setSymbol(highlightSymbol);
       	      break;
       	    case "polygon":
       	    	graphic.setSymbol(highlightFillSymbol);
       	      break;
       	  }  
       }

     //---------------------设施信息查询-----------------------------//
     //绑定概要信息
     function summaryInfo(graphic){
     	var point  = getGeometryCenter(graphic.geometry);
     	var roadName =  graphic.attributes["项目名称"];
     	var infoTemplate = new esri.InfoTemplate("概要信息", roadName+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;项目位置");
     	graphic.setInfoTemplate(infoTemplate);
     }

     function QueryRoadByName(name)
     {
     	
     }
    function showAllProjectInfo()
    {
    	if(allQueryResult.length==0) return;
    	for(var i=0;i<allQueryResult.length;i++)
    		{
    			var feature=allQueryResult[i];
    			var allattributs=feature.attributes;
    		}
    }
     function buildTemplateColumns(attributes) {
    	    var template  = "";
    	    for (var attribute in attributes) {
    	        if (attributes.hasOwnProperty(attribute)) {
    	        	var label = attribute;
    	            if(attribute === "SHAPE_Leng"||
    	        		   attribute === "Shape_Le_1"||
    	        		   attribute === "Shape_Length"||
    	        		   attribute === "OBJECTID"||
    	        		   attribute === "OBJECTID_1"||
    	        		   attribute === "Shape"||
    	        		   attribute === "Shape_Leng"||
    	        		   attribute === "Shape_Area"){
    	            	continue;
    	            }
    	            
    	            template = template +"<br><b>"+label+":</b>　";
    	            template = template +"${"+attribute+"}";
    	        }
    	    }
    	    return template;
    	}
     //通过输入图形查询交通规划图层要素
       function Queryjtgh(inputFeature)
       {
    	   var deferred;
    	   var deferred2;
    	   var searchurl="http://192.168.0.6:6080/arcgis/rest/services/longhua/jtgh/MapServer";
    	   identifyTask = new IdentifyTask(searchurl);
    	   var alllayerIds=GetAllLayerIds(searchurl);
           identifyParams = new IdentifyParameters();
           identifyParams.tolerance = 5;
           identifyParams.returnGeometry = true;
           identifyParams.layerIds =alllayerIds;
           identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_ALL;
           identifyParams.width = map.width;
           identifyParams.height = map.height;
           identifyParams.geometry = inputFeature.geometry;
           identifyParams.mapExtent = map.extent;
           deferred = identifyTask
           .execute(identifyParams)
           .addCallback(function (response) {
             return arrayUtils.map(response, function (result) {
               var feature = result.feature;
               var layerName = result.layerName;
               feature.attributes.layerName = layerName;
               /*var layerName = result.layerName;
               feature.attributes.layerName = layerName;
             	var infoTemplate = new esri.InfoTemplate(layerName,  buildTemplateColumns(feature.attributes));
               return feature;*/
               allQueryResult[allQueryResult.length]=feature;
              
             });
           });

           searchurl="http://192.168.0.6:6080/arcgis/rest/services/longhua/jtgh/MapServer";
           identifyTask = new IdentifyTask(searchurl);
    	   alllayerIds=[1,2,3];
           //identifyParams = new IdentifyParameters();
          // identifyParams.tolerance = 30;
          // identifyParams.returnGeometry = true;
           identifyParams.layerIds =alllayerIds;
          // identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_ALL;
          // identifyParams.width = map.width;
          // identifyParams.height = map.height;
          // identifyParams.geometry = inputFeature.geometry;
           //identifyParams.mapExtent = map.extent;
           deferred2 = identifyTask
           .execute(identifyParams)
           .addCallback(function (response) {
             return arrayUtils.map(response, function (result) {
               var feature = result.feature;
               var layerName = result.layerName;
               feature.attributes.layerName = layerName;
               /*var layerName = result.layerName;
               feature.attributes.layerName = layerName;
             	var infoTemplate = new esri.InfoTemplate(layerName,  buildTemplateColumns(feature.attributes));
               return feature;*/
               allQueryResult[allQueryResult.length]=feature;
              
             });
           });
           var dl = new DeferredList([deferred,deferred2]);
           
           dl.then(function(value){
        	 showPrjInfo(allQueryResult);
        	  }, function(err){
        	    // Do something when the process errors out
        	  }, function(update){
        	    // Do something when the process provides progress information
        	  });
    	 
    	
    	 
    	 /* var dl = new DeferredList();
    	  var allDefered=[];
    	   for(var i=0;i<alllayerIds.length;i++)
    		   {
    		  
    		      var tempurl=searchurl+"/"+alllayerIds[i];
    		      
			   	  var queryTask = new esri.tasks.QueryTask(tempurl);
			   	      query = new Query();
			          query.outSpatialReference = map.spatialReference;
			          query.geometry=inputFeature.geometry;
			          query.distance=50;
			          query.returnGeometry = true;
			          query.outFields = ["*"];
			        
			       var dlp=queryTask.execute(query, function(featureSet) {
    		   			var numFeatures = featureSet.features.length;
    		   	        for (var i=0; i<numFeatures; i++) {
    		   	          var graphic = featureSet.features[i];
    		   			   allQueryResult[allQueryResult.length]=graphic;
    		   		 	 }
    		   		  });
			       allDefered[allDefered.length]=dlp;
    		   }
    	   allDefered.then(ShowQueryInfo);*/
    	  
       }
     
     function showPrjInfo(arrays)
     {  
         var content  = '<div  id="d1">'+
         '<table id="tab1"  bordercolor="black"    border="1">'+
         '<tr><td colspan="7" class="tabTitle">相关项目工程表</td></tr>'+
         '<tr><th>序号</th><th>项目编号</th><th>项目名称</th><th>项目类型</th><th>规划时间</th><th>规划类型</th><th>规划来源</th></tr>';
    	 for(var i=0;i<arrays.length;i++){
    		 content+='<tr><td class="td1">'+(i+1)+'</td>'+
    		 		  '<td>'+changeOutPutStr(arrays[i].attributes["项目编号"])+'</td>'+
    		 		  '<td>'+changeOutPutStr(arrays[i].attributes["项目名称"])+'</td>'+
    		 		  '<td>'+changeOutPutStr(arrays[i].attributes.layerName)+'</td>'+
    		 		  '<td>'+changeOutPutStr(arrays[i].attributes["规划时间"])+'</td>'+
    		 		  '<td>'+changeOutPutStr(arrays[i].attributes["规划类型"])+'</td>'+
    		 		  '<td>'+changeOutPutStr(arrays[i].attributes["规划来源"])+'</td>'+
    		 		  '</tr>';
    		 		  
//     		 	var feature=arrays[i];
//     		 	feature.attributes["规划类型"]
    		 }
   		content+='</table>'+
		'</div>';
    	$('#mapDiv').append(content);
    	 var DivWidth = document.getElementById('d1').offsetWidth;
    	 var BodyWidth = document.body.clientWidth;
    	 document.getElementById('d1').style.left= (BodyWidth-DivWidth)*0.95+'px';

     }
     
     function changeOutPutStr(str){
    	 if(str=="Null"||str==undefined){
    		 return "";
    	 }else{
    		 return str;
    	 }
     }
     //通过图形查询交通微循环
     	function Queryjtwxh(inputFeature)
     	{
          var alllayerIds=["1","2","3"];
     	   var searchurl="http://192.168.0.6:6080/arcgis/rest/services/longhua/jtgh/MapServer";
     	   for(var i=0;i<alllayerIds.length;i++)
     		   {
     		      var tempurl=searchurl+"/"+allayerIds[i];
 			   	  var queryTask = new esri.tasks.QueryTask(tempurl);
 			   	      query = new esri.tasks.Query();
 			          //query.outSpatialReference = {"wkid": 102100};
 			          query.geometry=inputFeature.geometry;
 			          query.distance=10;
 			          query.returnGeometry = true;
 			          query.outFields = ["规划类型", "规划来源", "规划时间", "项目编号", "项目名称","项目来源","所在街道","项目位置","项目类别","项目阶段","技术等级 ","建设性质","建设规模 ","目前进展 ","责任单位"];
     		   		  queryTask.execute(query, function(featureSet) {
     		   			var numFeatures = featureSet.features.length;
     		   	        for (var i=0; i<numFeatures; i++) {
     		   	          var graphic = featureSet.features[i];
     		   			   allQueryResult[allQueryResult.length]=graphic;
     		   		 	 }
     		   		  });
     		   }     	
     	}
     	//获取所有图层ID
     	function GetAllLayerIds(MapUrl)
     	{
     		var TempMap = new ArcGISDynamicMapServiceLayer(MapUrl);
     		var layerIds=new Array();
     		if(TempMap!=null)
     			{
     			
     			for(var i=0;i<TempMap.layerInfos.length;i++)
     				{
     				
     				layerIds[i]=TempMap.LayerInfos[i].id;
     				}
     			}
     		return layerIds;
     	}
     	
    });